package com.study.studyfive.rabbitmq;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @date 2023/9/20
 * @description 发送消息
 */
@RestController
@Slf4j
@RequestMapping("test/rabbitmq")
public class DirectRabbitController{
    @Autowired
    RabbitTemplate rabbitTemplate;  // 使用RabbitTemplate,这提供了接收/发送等等方法

    @GetMapping("/sendDirectMsg")
    public String sendDirectMsg() {
        String msgId = String.valueOf(UUID.randomUUID());
        String msmData = "test msg:" + Math.random();

        String createTime = DateUtil.now();
        Map<String, Object> map = new HashMap<>();
        map.put("msgId", msgId);
        map.put("msmData", msmData);
        map.put("createTime", createTime);
        String payload = JSON.toJSONString(map);
        log.info("打印的消息："+ payload);
        // 如果写的是默认交换机，可以不传交换机名称
        // rabbitTemplate.convertAndSend("TestDirectRouting", payload);
        // 将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", payload);
        return "ok";
    }

    @GetMapping("/sendDirectMsg2")
    public String sendDirectMsg2() {
        System.out.println("sendDirectMsg2准备发送");
        String msgId = String.valueOf(UUID.randomUUID());
        String msmData = "test msg:" + Math.random();
        String createTime = DateUtil.now();
        Map<String, Object> map = new HashMap<>();
        map.put("msgId2", msgId);
        map.put("msmData2", msmData);
        map.put("createTime2", createTime);
        String payload = JSON.toJSONString(map);
        // 1.由于bindingDirect2绑定交换机使用的默认交换机，使用withQueueName表示用和队列名称相同的键值对
        // rabbitTemplate.convertAndSend("TestDirectQueue2", payload);
        // 2.将消息携带绑定键值：TestDirectRouting2 发送到交换机TestDirectExchange2
        // rabbitTemplate.convertAndSend("TestDirectExchange2", "TestDirectRouting2", payload);
        rabbitTemplate.convertAndSend("TestDirectExchange2", "TestDirectRouting2", payload);
        return "OK";
    }
}

